package com.example.demo.service.impl;

import com.example.demo.constant.RedisConstant;
import com.example.demo.service.TokenService;
import com.example.demo.utils.RedisService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/1/30 19:54
 */
@Service
public class TokenServiceImpl implements TokenService
{
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisService redisService;

    @Override
    public String createToken()
    {
        String str = UUID.randomUUID().toString().replace("-", "");
        StrBuilder token = new StrBuilder();
        try
        {
            token.append(RedisConstant.TOKEN_PREFIX).append(str);
            redisService.setEx(token.toString(), token.toString(), 10000L);
            boolean notEmpty = StringUtils.isNotEmpty(token.toString());
            if (notEmpty)
            {
                return token.toString();
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean checkToken(HttpServletRequest request) throws Exception
    {
        String token = request.getHeader(RedisConstant.TOKEN_NAME);
        if (StringUtils.isBlank(token))
        {
            // header中不存在token
            token = request.getParameter(RedisConstant.TOKEN_NAME);
            if (StringUtils.isBlank(token))
            {
                // parameter中也不存在token
                log.error("token为空！");
                return false;
            }
        }
        if (!redisService.exists(token))
        {
            log.error("token不存在！");
            return false;
        }
        boolean remove = redisService.remove(token);
        if (!remove)
        {
            log.error("移除失败！");
            return false;
        }
        return true;
    }
}
